package com.weiyi.weiman.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.weiyi.weiman.domain.Const.UserConst;
import com.weiyi.weiman.domain.dto.CollectComicsDTO;
import com.weiyi.weiman.domain.status.TokenStatus;
import com.weiyi.weiman.exception.TokenException;
import com.weiyi.weiman.mapper.user.ComicsCollectMapper;
import com.weiyi.weiman.mapper.user.UserMapper;
import com.weiyi.weiman.service.user.UserService;
import com.weiyi.weiman.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import user.ComicsCollect;
import user.User;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author zhang
 * @Date 2021/5/11 下午12:01
 * @Description 用户公共的业务类
 * @Version 1.0
 **/
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    ComicsCollectMapper collectMapper;
    @Autowired
    RedisUtils redisUtils;

    @Override
    public User getUser(long userId) {
        String userKey = UserConst.USER_DETAIL + userId;
        User user = null;
        log.info("查找用户:{}", userId);
        if (!redisUtils.hasKey(userKey)) {
            log.info("用户:"+userId+"不在缓存中");
            user = userMapper.selectById(userId);
            if (Objects.isNull(userId)) {
                log.error(userId+"用户不存在");
                throw new TokenException(TokenStatus.TOKEN_ERROR);
            }
            HashMap<String,String> comicsMap = JSON.parseObject(JSON.toJSONString(user)
                    , new TypeReference<HashMap<String,String>>(){});
            redisUtils.hPutAll(userKey, comicsMap);
            log.info("用户:"+userId+"已加入缓存中");
        } else {
            //获取redis中comics的数据，并转为comics对象
            Map<Object, Object> comicsMap = redisUtils.hGetAll(userKey);
            user = JSON.parseObject(JSON.toJSONString(comicsMap), User.class);
            log.info("用户{}在缓存中,已获取数据", userId);
        }
        return user;
    }

    @Override
    public boolean isCollected(long userId, long comicsId) {
        String collectKey = UserConst.USER_COLLECT_PRE + userId;
        if (redisUtils.hExists(collectKey, comicsId+""))
            return true;
        QueryWrapper<ComicsCollect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("comics_id", comicsId).eq("user_id", userId);
        return !Objects.isNull(collectMapper.selectOne(queryWrapper));
    }
}
